import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class InorderTraversal {
    // leetcode 二叉树的中序遍历
    // https://leetcode.cn/problems/binary-tree-inorder-traversal/description/?envType=study-plan-v2&envId=top-100-liked
    /**
     * 递归实现
     */
    private List<Integer> ret = new ArrayList<>();
    public List<Integer> inorderTraversal1(TreeNode root) {
        inorder(root);
        return ret;
    }

    private void inorder(TreeNode root) {
        if (root == null) return;
        inorder(root.left);
        ret.add(root.val);
        inorder(root.right);
    }

    /**
     * 非递归实现
     * @param root
     * @return
     */
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> ret = new ArrayList<>();
        if(root == null) return ret;
        Stack<TreeNode> stack = new Stack<>();
        while (!stack.isEmpty() || root != null) {
            while (root != null) {
                stack.add(root);
                root = root.left;
            }
            root = stack.pop();
            ret.add(root.val);
            root = root.right;
        }
        return ret;
    }

    public static void main(String[] args) {
        InorderTraversal inorderTraversal = new InorderTraversal();
        TreeNode A = new TreeNode(1);
        TreeNode B = new TreeNode(2);
        TreeNode C = new TreeNode(3);
        A.right = B;
        B.left = C;
        System.out.println(inorderTraversal.inorderTraversal(A));
    }
}
